//
//  WFCUFCircleDetailVC.m
//  WFChatUIKit
//
//  Created by 陈*敏 on 2/6/2024.
//  Copyright © 2024 Tom Lee. All rights reserved.
//

#import "WFCUFCircleDetailVC.h"
#import "YGExtendChain.h"
#import "SDAutoLayout.h"
#import "AFNetworking.h"
#import <WFChatClient/WFCChatClient.h>
#import "WFCUPostDynamicVC.h"
#import "WFCUImage.h"

#import <ZLPhotoBrowser/ZLPhotoBrowser-Swift.h>
#import <Photos/Photos.h>
#import "MBProgressHUD.h"
#import "UIView+Toast.h"
#import "WFCUConfigManager.h"


#import "MomentCell.h"
#import "Moment.h"
#import "Comment.h"
#import "SHPublishViewController.h"
#import "XJJRefresh.h"
#import "MJRefresh.h"

#import "UIView+Geometry.h"
#import "SDWebImage/UIImageView+WebCache.h"
#import "CLInputToolbar.h"
#import "WFCUFCircleDetailVC.h"

#define kStatusBarH ([[UIApplication sharedApplication] statusBarFrame].size.height)
//背景自己
#define kActionSheet_BackGroup_Me_Tag 1
//背景其他人
#define kActionSheet_BackGroup_Other_Tag 2

@interface WFCUFCircleDetailVC ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *photos;
 

@property (nonatomic, strong)UIView * popView ;
  

@property (nonatomic,strong) WFCCUserInfo *me;



@property (nonatomic,strong) UIView *barBackgroundView;
@property (nonatomic, strong) CLInputToolbar *inputToolbar;
 
@end

@implementation WFCUFCircleDetailVC



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

//    self.navigationController.navigationBar.hidden = YES;
    NSMutableArray *barSubviews = [NSMutableArray array];
    //将导航栏的子控件添加到数组当中,取首个子控件设置透明度(防止导航栏上存在非导航栏自带的控件)
    for (UIView * view in self.navigationController.navigationBar.subviews) {
        if(![view isMemberOfClass:[UIView class]]){
            [barSubviews addObject:view];
        }
    }
    UIView *barBackgroundView = [barSubviews firstObject];
    barBackgroundView.alpha   = 1;

    [self.navigationController.navigationItem.backBarButtonItem setImage:[WFCUImage imageNamed:@"back_white"]];
    
    UIBarButtonItem *barck = self.navigationController.navigationItem.backBarButtonItem;
    [barck setImage:[UIImage imageNamed:@"back_white"]] ;
    NSLog(@"barck %@ ",barck ) ;
    
}

 


- (void)onBackBtn:(UIButton *)completion {
    
    [self.navigationController popViewControllerAnimated:YES];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
 
    
 
    //    back_white
    
    self.view.backgroundColor = [UIColor whiteColor] ; // [WFCUConfigManager globalManager].backgroudColor;

    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, ZmNavigationHeight_N(), self.view.frame.size.width, self.view.frame.size.height -  ZmNavigationHeight_N()) style:UITableViewStylePlain];
    if (@available(iOS 15, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    }
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.backgroundColor = [UIColor clearColor];
    if ([self.tableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        if (@available(iOS 11.0, *)) {
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        }
    }
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.separatorColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0];
    self.tableView.separatorInset = UIEdgeInsetsZero;
    self.tableView.tableFooterView = [UIView new];
     [self.view addSubview:self.tableView];

    
 
    self.me = [[WFCCIMService sharedWFCIMService] getUserInfo:[WFCCNetworkService sharedInstance].userId refresh:NO];

 
    self.navigationItem.title= @"详情";
 
    [self setTextViewToolbar];

    
}
-(void)setTextViewToolbar {
    
    
    self.inputToolbar = [[CLInputToolbar alloc] init];
    self.inputToolbar.textViewMaxLine = 3;
    self.inputToolbar.fontSize = 15;
    self.inputToolbar.placeholder = @"Comments" ;
    WEAKSELF_ZM
 
 
    self.inputToolbar.btnsBlock = ^(UIButton *btn) {
 
    };
    [self.view addSubview:self.inputToolbar];
    
    
}
   


#pragma mark - Getter
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight) style:UITableViewStylePlain];

//        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -(44 + kStatusBarH), kWidth, kHeight) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _tableView.separatorColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0];
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];

    }
    return _tableView;
}
 
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
 
#pragma mark - MomentCellDelegate
// 点击用户头像
- (void)didClickHead:(MomentCell *)cell
{
    NSLog(@"击用户头像");
}
// 赞
- (void)didLikeMoment:(MomentCell *)cell
{
    NSLog(@"点击了====菜单");
    
    __block BOOL isLike = NO;
    
    NSInteger index = [self.dataArray indexOfObject:cell.moment];
    
    //查看点赞列表是否有自己
    if ([cell.moment.praiseNameList containsString:self.me.displayName]) {
        isLike = YES;
    }
    //    __weak typeof(self) weakSelf = self;
    NSMutableString *muString = [NSMutableString string];
    if(cell.moment.praiseNameList.length > 0) {
        [muString appendString:cell.moment.praiseNameList];
    }
    
  
    
    
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"加载中...";
    [hud showAnimated:YES];
//    /topic/sendTopic
    
    NSString *authToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"WFC_APPSERVER_AUTH_TOKEN"];
    NSString *userId = [WFCCNetworkService sharedInstance].userId;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
    //在调用其他接口时需要把cookie传给后台，也就是设置cookie的过程

    if(authToken.length) {
        [manager.requestSerializer setValue:authToken forHTTPHeaderField:@"authToken"];
 
    }
 
    
    WEAKSELF_ZM
    NSDictionary *parameters = @{@"topicId":cell.moment.topicId  }; ///<.TEXT, IMAGE, VIDEO
   
    NSString *url = isLike ? [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/cancelLike/%@" , cell.moment.topicId] : [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/like/%@" , cell.moment.topicId];
//    {\"text\":\"文字内容\",\"imgList\":[\"http://111\",\"http://222\"],\"videoList\":[\"http:111\",\"http://222\"]}")
    [manager GET:url
       parameters:parameters
         progress:nil
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [hud hideAnimated:YES];
            NSDictionary *dic = responseObject;
            NSLog(@" ret---  %@ ", dic );

            if([dic[@"code"] intValue] == 200) {
                
     
                
                if (isLike) {//点过赞了
                    NSRange range1 = [cell.moment.praiseNameList rangeOfString:[@"," stringByAppendingString:weakSelf.me.displayName]];
                    NSRange range2 = [cell.moment.praiseNameList rangeOfString:weakSelf.me.displayName];
                    if(range1.length) {
                        cell.moment.praiseNameList = [muString substringToIndex:range1.location];
                    } else if(range2.length) {
                        cell.moment.praiseNameList = [muString substringToIndex:range2.location];
                    }
                }else{
                    
                    if([cell.moment.praiseNameList isEqualToString:@""] || (cell.moment.praiseNameList == nil)){
                        cell.moment.praiseNameList = [muString stringByAppendingString:weakSelf.me.displayName];
                    } else {
                        cell.moment.praiseNameList = [muString stringByAppendingString:[@"," stringByAppendingString:weakSelf.me.displayName]];
                    }
                     
                }
                
                [weakSelf.dataArray replaceObjectAtIndex:index withObject:cell.moment];
                //进行刷新
                [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
              
                
                
                
            }else{
                
                
            }
 
            
            
        });
 
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error) {
            
            NSLog(@" ret---  %@ ", error );
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [hud hideAnimated:YES];

            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.label.text = error.localizedDescription;
            //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
            [hud hideAnimated:YES afterDelay:1.f];
        });
        
    }];
    
    
    
    
    
}
// 评论
- (void)didAddComment:(MomentCell *)cell
{
    NSLog(@"评论");
    
    NSInteger index = [self.dataArray indexOfObject:cell.moment];

    WEAKSELF_ZM
    [self.inputToolbar inputToolbarSendText:^(NSString *text) {

        
        
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.label.text = @"加载中...";
        [hud showAnimated:YES];
    //    /topic/sendTopic
        
        NSString *authToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"WFC_APPSERVER_AUTH_TOKEN"];
//        NSString *userId = [WFCCNetworkService sharedInstance].userId;
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
        
        //在调用其他接口时需要把cookie传给后台，也就是设置cookie的过程

        if(authToken.length) {
            [manager.requestSerializer setValue:authToken forHTTPHeaderField:@"authToken"];
     
        }
     
        
        WEAKSELF_ZM
        NSDictionary *parameters = @{ @"content":text ,@"replyId":cell.moment.topicId,@"replyType":@"1" }; ///<.TEXT, IMAGE, VIDEO
     
        NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/reply"  ];
    //    {\"text\":\"文字内容\",\"imgList\":[\"http://111\",\"http://222\"],\"videoList\":[\"http:111\",\"http://222\"]}")
        [manager POST:url
           parameters:parameters
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                

                NSDictionary *dic = responseObject;
                [hud hideAnimated:YES];
                NSLog(@" ret---  %@ ", dic );

                if([responseObject[@"code"] intValue] == 200) {
                    
                    NSDictionary *obj = [dic handleNullObjectForKey:@"data"];
                    
                    
                    NSMutableArray *reply = cell.moment.commentList.mutableCopy;
                    
                    Comment *comment = [[Comment alloc] init];
                    comment.userName = [obj handleNullObjectForKey:@"displayName"];
                    comment.text = [obj handleNullObjectForKey:@"content"];
                    comment.time = [NSObject retWithLongDate:[obj handleNullObjectForKey:@"createTime"]];
                    comment.pk = 0;
                    comment.replyId = [obj handleNullObjectForKey:@"replyId"];
                    [reply addObject:comment];
                    
                    
                    cell.moment.commentList = reply;
 

                    [weakSelf.dataArray replaceObjectAtIndex:index withObject:cell.moment];
                    //进行刷新
                    [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                  
                    
                    
                    
                }else{
                    
                    
                }
     
                
                
            });
     
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            if (error) {
                
                NSLog(@" ret---  %@ ", error );
                
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [hud hideAnimated:YES];

                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.label.text = error.localizedDescription;
                //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                [hud hideAnimated:YES afterDelay:1.f];
            });
            
        }];
        
        
        
    }];
    [self.inputToolbar popToolbar];
}
 


// 查看全文/收起
- (void)didSelectFullText:(MomentCell *)cell
{
    NSLog(@"全文/收起");
    
    [self.tableView reloadData];
}
// 删除
- (void)didDeleteMoment:(MomentCell *)cell
{
    NSLog(@"删除");
    
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"加载中...";
    [hud showAnimated:YES];
//    /topic/sendTopic
    
    NSString *authToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"WFC_APPSERVER_AUTH_TOKEN"];
    NSString *userId = [WFCCNetworkService sharedInstance].userId;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
    //在调用其他接口时需要把cookie传给后台，也就是设置cookie的过程

    if(authToken.length) {
        [manager.requestSerializer setValue:authToken forHTTPHeaderField:@"authToken"];
 
    }
 
    
    WEAKSELF_ZM
    NSDictionary *parameters = @{@"topicId":cell.moment.topicId  }; ///<.TEXT, IMAGE, VIDEO
 
    NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/removeTopic/%@" , cell.moment.topicId];
//    {\"text\":\"文字内容\",\"imgList\":[\"http://111\",\"http://222\"],\"videoList\":[\"http:111\",\"http://222\"]}")
    [manager GET:url
       parameters:parameters
         progress:nil
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [hud hideAnimated:YES];
            NSDictionary *dic = responseObject;
            NSLog(@" ret---  %@ ", dic );

            if([dic[@"code"] intValue] == 200) {
                
            
                NSInteger index = cell.tag;
                //数组中移除
                [weakSelf.dataArray removeObjectAtIndex:index];
                //刷新表格
                [weakSelf.tableView reloadData];
                
                
            }else{
                
                
            }
 
            
            
        });
 
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error) {
            
            NSLog(@" ret---  %@ ", error );
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [hud hideAnimated:YES];

            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.label.text = error.localizedDescription;
            //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
            [hud hideAnimated:YES afterDelay:1.f];
        });
        
    }];
    
    
    
    
}
// 选择评论
- (void)didSelectComment:(Comment *)comment
{
    NSLog(@"点击评论");
}
// 点击高亮文字
- (void)didClickLink:(MLLink *)link linkText:(NSString *)linkText momentCell:(MomentCell *)cell
{
    if(link.linkType == MLLinkTypeURL) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:linkText]];
    } else if(link.linkType == MLLinkTypeEmail) {
        NSString *recipients = @"mailto:cheerylau@126.com";
        NSString *email = [NSString stringWithFormat:@"%@", recipients];
        email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
    } else if(link.linkType == MLLinkTypePhoneNumber) {
        NSString *mobileNumber = [NSString stringWithFormat:@"tel://%@", linkText];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mobileNumber]];
    }
    NSLog(@"点击高亮文字：%@",linkText);
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"MomentCell";
    MomentCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[MomentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor whiteColor];
    }
    cell.tag = indexPath.row;
    cell.moment = [self.dataArray objectAtIndex:indexPath.row];
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = [MomentCell momentCellHeightForMoment:[self.dataArray objectAtIndex:indexPath.row]];
    return height;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
   
    
    return nil;

    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
  
    
}
#pragma mark - UITableViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSIndexPath *indexPath =  [self.tableView indexPathForRowAtPoint:CGPointMake(scrollView.contentOffset.x, scrollView.contentOffset.y)];
    MomentCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    cell.menuView.show = NO;
 
    
    [self.view endEditing:YES];

}
 

 
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
